<!--
 * @Author: zzr
 * @Date: 2024-12-28 12:36:10
 * @LastEditors: zzr
 * @Description: 
-->
<!--
 * @Author: zzr
 * @Date: 2024-12-03 17:18:42
 * @LastEditors: zzr
 * @Description: 
-->
<template>
  <div style="height: 100%">
    <div class="page-video">
      <div class="inner custom-scroll">
        <div class="left-box">
          <div class="page-title">
            <!-- <img src="/images/video/video-space-title.png" /> -->
          </div>
          <div class="video-params">
            <el-form :model="params" label-width="80px" label-position="left">
              <el-page-header
                :icon="ArrowLeft"
                class="t-white mt-5 mb-20"
                @back="router.back()"
              >
                <template #content>
                  <span class="text-large font-600 mr-3 t-white">整活R</span>
                </template>
              </el-page-header>
              <div class="video-box">
                <div class="param-line">
                  <div class="title" style="margin-top: 0">
                    <span class="title-text">图片（必填）：</span>
                  </div>
                </div>
                <div class="param-line img-uploader">
                  <div class="img-list-box" v-if="imgList.length">
                    <div
                      class="img-item flex-h flex-center pt-20 pb-20"
                      v-for="imgURL in imgList"
                    >
                      <div class="image-container flex-h flex-center">
                        <el-image
                          :src="imgURL"
                          fit="cover"
                          style="border-radius: 5px"
                        />
                        <div class="overlay ft-18 t-white">
                          <el-icon
                            @click="removeUploadImage(imgURL)"
                            class="mr-12 cursor"
                            ><Delete
                          /></el-icon>
                          <el-icon
                            class="cursor t-white"
                            @click="uploadDialogVisivle = true"
                            ><UploadFilled
                          /></el-icon>
                        </div>
                      </div>
                      <div class="flex-1 pl-10 pr-10">
                        <div class="slider-demo-block flex-v flex-center">
                          <span class="demonstration"
                            ><p class="t-white ft-12">
                              参考强度<span class="ft-10 t-gray"
                                >（数值越大参考强度越大）</span
                              >
                            </p></span
                          >
                          <el-slider
                            v-model="params.imageFidelity"
                            :step="0.25"
                            :max="1"
                            :marks="marks"
                          />
                        </div>
                      </div>
                    </div>
                  </div>
                  <el-upload
                    v-else
                    class="img-uploader mt-10"
                    ref="upload"
                    :auto-upload="true"
                    :show-file-list="false"
                    :http-request="uploadImg"
                    accept=".png,.jpg,.jpeg,.bmp"
                    drag
                    style="--el-color-primary: #47fff1"
                    :limit="1"
                  >
                    <!-- <el-icon class="uploader-icon">
                      <Plus />
                    </el-icon> -->
                    <div class="el-upload__text flex-h flex-center">
                      <i class="iconfont icon-upload liner-text mr-5">
                        <UploadFilled />
                      </i>
                      <span class="ft-12 liner-text">点击/拖拽</span>
                    </div>
                    <template #tip>
                      <div class="el-upload__tip ft-11 base-color">
                        提示：支持 JPG / PNG
                        格式，文件大小不超过10MB，尺寸不小于300PX
                      </div>
                    </template>
                  </el-upload>
                </div>
              </div>
              <div class="video-box">
                <div class="param-line pt">
                  <div class="title">
                    <!-- <img
                          class="title-icon"
                          src="/images/video/creativity.svg"
                        /> -->
                    <span class="title-text">图片创意描述（非必填）：</span>
                  </div>
                </div>
                <div class="param-line">
                  <el-input
                    v-model="params.prompt"
                    :autosize="{ minRows: 6, maxRows: 10 }"
                    type="textarea"
                    ref="promptRef"
                    placeholder="请输入要生成的内容"
                  />
                </div>
              </div>
              <div class="video-box">
                <div class="param-line">
                  <div class="title">
                    <!-- <img
                          class="title-icon"
                          src="/images/video/creativity.svg"
                        /> -->
                    <span class="title-text">参数设置：</span>
                  </div>
                </div>
                <div class="param-line">
                  <el-row class="video-slider flex-h">
                    <div
                      class="video-slider-title text-left left-box-label ft-12 sun-color mr-15"
                    >
                      创意想象力
                    </div>
                    <div class="flex-1">
                      <el-slider
                        v-model="params.cfg_scale"
                        :max="1"
                        :step="0.05"
                        :format-tooltip="formatCreativityTooltip"
                        style="--el-slider-button-size: 14px"
                      />
                    </div>
                    <div
                      class="video-slider-title text-right ml-15 ft-12 sun-color"
                    >
                      创意相关性
                    </div>
                  </el-row>
                </div>
                <div class="param-line flex-h flex-hv-center">
                  <span class="left-box-label ft-12 sun-color">视频模式</span>
                  <div class="form-item-inner">
                    <el-radio-group
                      v-model="params.mode"
                      style=""
                    >
                      <el-radio
                        :value="radioItem.value"
                        v-for="radioItem in schedulers"
                        >{{ radioItem.label }}</el-radio
                      >
                    </el-radio-group>
                  </div>
                </div>
                <div class="param-line flex-h flex-hv-center">
                  <span class="left-box-label ft-12 sun-color">视频时长</span>
                  <div class="form-item-inner">
                    <el-radio-group
                      v-model="params.duration"
                      style=""
                    >
                      <el-radio
                        :value="radioItem.value"
                        v-for="radioItem in durationOption"
                        >{{ radioItem.label }}
                      </el-radio>
                    </el-radio-group>
                  </div>
                </div>
              </div>
              <div class="video-box mb-20">
                <div class="param-line">
                  <div class="title">
                    <!-- <img
                          class="title-icon"
                          src="/images/video/unnecessary.svg"
                        /> -->
                    <span class="title-text">不希望呈现的内容（非必填）：</span>
                  </div>
                </div>

                <div class="param-line mt-10">
                  <el-input
                    v-model="params.negative_prompt"
                    :autosize="{ minRows: 8, maxRows: 10 }"
                    type="textarea"
                    placeholder="写下你不希望在视频中呈现的内容。例如：动画、模糊、变形、毁容、低质量、拼贴、粒状、标志、抽象、插图、计算机生成、扭曲 …"
                  />
                </div>
              </div>
              <!-- <div class="text-info">
                <el-row :gutter="10">
                  <el-col :span="12">
                    <el-tag>单次绘图消耗{{ klingPower }}算力</el-tag>
                  </el-col>
                  <el-col :span="12">
                    <el-tag type="success">当前可用{{ power }}算力</el-tag>
                  </el-col>
                </el-row>
              </div> -->
            </el-form>
          </div>
          <div class="submit-btn">
            <el-tooltip :visible="tooltipVisivle && btnSubmiteStatus">
              <template #content>
                <span>{{
                  activeName == "text2video" ? "请输入创意描述" : "请上传图片"
                }}</span>
              </template>
              <el-button
                v-loading="!!runningJobs.length"
                :dark="false"
                @mouseenter="tooltipVisivle = true"
                @mouseleave="tooltipVisivle = false"
                round
                @click="generate"
                :disabled="btnSubmiteStatus || !!runningJobs.length"
                class="liner-btn-opacity liner-btn"
                >开始创作</el-button
              >
            </el-tooltip>
          </div>
        </div>
        <div class="flex-1 p-10 flex-h flex-center">
          <video-player
            v-if="videoData"
            ref="videoPlayerRef"
            :src="videoData.img"
            :options="playerOptions"
            :autoplay="true"
          />
          <!-- :poster="poster" -->
          <template v-else>
            <div
              v-if="runningJobs.length"
              v-loading="!!runningJobs.length"
              v-for="(item, index) in runningJobs"
              element-loading-text="生成中..."
              class="flex-1 runjob-box"
            ></div>
            <Empty
              v-else
              image="/images/goose.gif"
              description="只要有视频，就能记录下时代的脉搏。"
            />
          </template>
        </div>
        <div class="task-list-box">
          <div class="task-list-inner h100">
            <div class="job-list-box flex-v h100">
              <!-- <h2>任务列表</h2>
              <task-list :list="runningJobs" /> -->

              <h2 class="ml-20 ft-16">历史</h2>
              <div
                class="finish-job-list waterfall-box flex-1 pr-10"
                v-infinite-scroll="fetchFinishJobs"
                :infinite-scroll-distance="20"
                v-if="finishedJobs.length > 0"
              >
                <!-- :colWidth="colWidth" -->
                <div
                  v-for="(item, index) in finishedJobs"
                  class="job-item"
                  :class="{ active: index == current }"
                >
                  <div
                    class="video-mask"
                    @click="videoClickHandle(item, index)"
                  ></div>
                  <video-player
                    ref="videoPlayerRef"
                    :src="item.img"
                    :options="playerOptions"
                    :autoplay="false"
                  />
                  <div class="gallery-icon flex-h">
                    <div class="gallery-icon-inner mr-10">
                      <el-icon @click.stop="downloadVideoHandle(item)" class=""
                        ><Download
                      /></el-icon>
                    </div>
                    <div class="gallery-icon-inner">
                      <el-icon @click.stop="removeVideo(item)"
                        ><Delete
                      /></el-icon>
                    </div>
                  </div>
                </div>
                <!-- <div class="no-more-data" v-if="isOver">
                  <span>没有更多数据了</span>
                  <i class="iconfont icon-face"></i>
                </div> -->
              </div>
              <el-empty :image-size="100" v-else />
              <!-- end finish job list-->
            </div>
          </div>
        </div>
        <!-- end task list box -->
      </div>

      <!-- 任务详情弹框 -->
      <el-dialog
        v-model="showTaskDialog"
        title="生成视频详情"
        :fullscreen="true"
      >
        <el-row :gutter="20">
          <el-col :span="16">
            <div
              class="img-container"
              :style="{ maxHeight: fullImgHeight + 'px' }"
            >
              <el-image :src="item['img_url']" fit="contain" />
            </div>
          </el-col>
          <el-col :span="8">
            <div class="task-info">
              <div class="info-line">
                <el-divider> 正向提示词 </el-divider>
                <div class="prompt">
                  <span>{{ item.prompt }}</span>
                  <el-icon
                    class="copy-prompt-sd"
                    :data-clipboard-text="item.prompt"
                  >
                    <DocumentCopy />
                  </el-icon>
                </div>
              </div>

              <div class="info-line">
                <el-divider> 反向提示词 </el-divider>
                <div class="prompt">
                  <span>{{ item.params.negative_prompt }}</span>
                  <el-icon
                    class="copy-prompt-sd"
                    :data-clipboard-text="item.params.negative_prompt"
                  >
                    <DocumentCopy />
                  </el-icon>
                </div>
              </div>

              <!-- <div class="info-line">
                <div class="wrapper">
                  <label>采样方法：</label>
                  <div class="item-value">{{ item.params.sampler }}</div>
                </div>
              </div> -->
              <div class="info-line">
                <div class="wrapper">
                  <label>图片比例：</label>
                  <div class="item-value">
                    {{ item.params.width }} x {{ item.params.height }}
                    <el-tooltip
                      effect="light"
                      content="生成图片的尺寸比例"
                      placement="right"
                    >
                      <el-icon>
                        <InfoFilled />
                      </el-icon>
                    </el-tooltip>
                  </div>
                </div>
              </div>

              <div class="info-line">
                <div class="wrapper">
                  <label>迭代步数：</label>
                  <div class="item-value">{{ item.params.steps }}</div>
                </div>
              </div>

              <div class="info-line">
                <div class="wrapper">
                  <label>引导系数：</label>
                  <div class="item-value">{{ item.params.cfg_scale }}</div>
                </div>
              </div>

              <div class="info-line">
                <div class="wrapper">
                  <label>随机因子：</label>
                  <div class="item-value">{{ item.params.seed }}</div>
                </div>
              </div>

              <div v-if="item.params.hd_fix">
                <el-divider> 高清修复 </el-divider>
                <div class="info-line">
                  <div class="wrapper">
                    <label>重绘幅度：</label>
                    <div class="item-value">
                      {{ item.params.hd_redraw_rate }}
                    </div>
                  </div>
                </div>

                <div class="info-line">
                  <div class="wrapper">
                    <label>放大算法：</label>
                    <div class="item-value">{{ item.params.hd_scale_alg }}</div>
                  </div>
                </div>

                <div class="info-line">
                  <div class="wrapper">
                    <label>放大倍数：</label>
                    <div class="item-value">{{ item.params.hd_scale }}</div>
                  </div>
                </div>

                <div class="info-line">
                  <div class="wrapper">
                    <label>迭代步数：</label>
                    <div class="item-value">{{ item.params.hd_steps }}</div>
                  </div>
                </div>
              </div>

              <div class="copy-params">
                <el-button type="primary" round @click="copyParams(item)"
                  >画一张同款的</el-button
                >
              </div>
            </div>
          </el-col>
        </el-row>
      </el-dialog>
      <el-dialog v-model="dialogVisible">
        <img w-full :src="dialogImageUrl" alt="Preview Image" />
      </el-dialog>
    </div>
    <el-dialog
      v-model="uploadDialogVisivle"
      title="上传图片"
      width="500"
      v-if="uploadDialogVisivle"
    >
      <el-upload
        class="img-uploader"
        ref="dialogupload"
        :auto-upload="true"
        :show-file-list="false"
        :http-request="uploadImg"
        accept=".png,.jpg,.jpeg,.bmp"
        drag
        style="--el-color-primary: #47fff1"
      >
        <!-- <el-icon class="uploader-icon">
                    <Plus />
                  </el-icon> -->
        <div class="el-upload__text flex-h flex-center">
          <i class="iconfont icon-upload liner-text mr-5">
            <UploadFilled />
          </i>
          <span class="ft-12 liner-text">点击/拖拽</span>
        </div>
        <template #tip>
          <div class="el-upload__tip t-blue ft-12" style="color: #5a566d">
            提示：支持 JPG / PNG 格式，文件大小不超过10MB，尺寸不小于300PX
          </div>
        </template>
      </el-upload>
    </el-dialog>
  </div>
</template>

<script setup>
import { onMounted, onUnmounted, ref, watch, reactive, computed } from "vue";
import {
  Delete,
  DocumentCopy,
  InfoFilled,
  Orange,
  Picture,
  UploadFilled,
  ChatLineSquare,
  Download,
  ArrowLeft 
} from "@element-plus/icons-vue";
import { httpGet, httpPost } from "@/utils/http";
import { ElMessage, ElMessageBox, ElNotification } from "element-plus";
import Clipboard from "clipboard";
import { checkSession, getSystemInfo } from "@/store/cache";
import { useRouter, useRoute } from "vue-router";
import { getSessionId } from "@/store/session";
import { useSharedStore } from "@/store/sharedata";
import TaskList from "@/components/TaskList.vue";
import { copyObj, removeArrayItem } from "@/utils/libs";
import Compressor from "compressorjs";
import { downloadVideo } from "@/utils/dom";
import Empty from "@/components/Empty.vue";

const listBoxHeight = ref(0);
// const paramBoxHeight = ref(0)
const fullImgHeight = ref(window.innerHeight - 60);
const showTaskDialog = ref(false);
const item = ref({});
const isLogin = ref(false);
const loading = ref(true);
const colWidth = ref(220);
const tooltipVisivle = ref(false);
const uploadDialogVisivle = ref(false);
const store = useSharedStore();
const roles = ref([
  { label: "整活儿K", value: "keling" },
  { label: "整活儿R", value: "runway" },
]);
// text2video
// image2video
const activeName = ref("image2video");
const resizeElement = function () {
  listBoxHeight.value = window.innerHeight - 80;
  // paramBoxHeight.value = window.innerHeight - 200
};
resizeElement();
window.onresize = () => {
  resizeElement();
};
const samplers = [
  "Euler a",
  "DPM++ 2S a",
  "DPM++ 2M",
  "DPM++ SDE",
  "DPM++ 2M SDE",
  "UniPC",
  "Restart",
];
const durationOption = [
  {
    label: "5s",
    value: "5",
  },
  {
    label: "10s",
    value: "10",
  },
];
const schedulers = [
  {
    label: "标准",
    value: "std",
  },
  {
    label: "高品质",
    value: "pro",
  },
];
const scaleAlg = ["Latent", "ESRGAN_4x", "R-ESRGAN 4x+", "SwinIR_4x", "LDSR"];
const imgList = ref([]);
// const imgList = ref(["http://localhost:8888/images/vip.png"]);
const marks = reactive({
  0: "弱",
  0.25: "较弱",
  0.5: "中",
  0.75: "较强",
  1: "强",
});
const rates = [
  { css: "square", value: "1:1", text: "1:1", img: "/images/mj/rate_1_1.png" },
  // { css: "size1-2", value: "1:2", text: "1:2", img: "/images/mj/rate_1_2.png" },
  // { css: "size2-1", value: "2:1", text: "2:1", img: "/images/mj/rate_2_1.png" },
  // { css: "size2-3", value: "2:3", text: "2:3", img: "/images/mj/rate_3_4.png" },
  // { css: "size3-2", value: "3:2", text: "3:2", img: "/images/mj/rate_4_3.png" },
  // { css: "size3-4", value: "3:4", text: "3:4", img: "/images/mj/rate_3_4.png" },
  // { css: "size4-3", value: "4:3", text: "4:3", img: "/images/mj/rate_4_3.png" },
  {
    css: "size16-9",
    value: "16:9",
    text: "16:9",
    img: "/images/mj/rate_16_9.png",
  },
  {
    css: "size9-16",
    value: "9:16",
    text: "9:16",
    img: "/images/mj/rate_9_16.png",
  },
];
const route = useRoute();
const model = route.params.model;
const modelMap = {
  runway: "first",
};
const resetParams = {
  position: modelMap[model],
  imageFidelity: 0.75,
  width: 1024,
  height: 1024,
  sampler: samplers[0],
  mode: schedulers[0].value,
  seed: -1,
  steps: 20,
  hd_fix: false,
  hd_redraw_rate: 0.7,
  hd_scale: 2,
  hd_scale_alg: scaleAlg[0],
  hd_steps: 0,
  prompt: "",
  negative_prompt: "",
  fileList: [],
  //   ⽣成视频的⾃由t¦值b⼤，模型⾃由tb⼩，?⽤户输·的提⽰词相Ó性b
  cfg_scale: 0.5,
  // 横纵比
  aspect_ratio: "1280:768",
  // image2video
  type: "image2video",
  duration: durationOption[0].value,
  image: "",
};
const params = ref({ ...resetParams });

const btnSubmiteStatus = computed(() => {
  return (
    (!params.value.prompt && activeName.value == "text2video") ||
    (!params.value.image && activeName.value == "image2video")
  );
});
const dialogImageUrl = ref("");
//视频播放器
const videoPlayerRef = ref();

const dialogVisible = ref(false);

// 视频标题
const title = ref("");
title.value = "小学生写作业";
//视频封面
const poster = ref();
// 视频链接地址
// const videoData = ref("http://localhost:8888/files/aa.mp4");
const videoData = ref(null);

// 视频播放器配置
let playerOptions = ref({
  height: 1100,
  // width: document.documentElement.clientWidth, //播放器宽度
  playbackRates: [0.7, 1.0, 1.5, 2.0], // 播放速度
  muted: false, // 默认情况下将会消除任何音频。
  loop: false, // 导致视频一结束就重新开始。
  preload: "auto", // 建议浏览器在<video>加载元素后是否应该开始下载视频数据。auto浏览器选择最佳行为,立即开始加载视频（如果浏览器支持）
  language: "zh-CN",
  aspectRatio: "16:9", // 将播放器置于流畅模式，并在计算播放器的动态大小时使用该值。值应该代表一个比例 - 用冒号分隔的两个数字（例如"16:9"或"4:3"）
  fluid: true, // 当true时，Video.js player将拥有流体大小。换句话说，它将按比例缩放以适应其容器。
  notSupportedMessage: "此视频暂无法播放，请稍后再试", // 允许覆盖Video.js无法播放媒体源时显示的默认信息。
  controls: true,
  controlBar: {
    timeDivider: true,
    durationDisplay: true,
    remainingTimeDisplay: false,
    fullscreenToggle: true, // 全屏按钮
  },
});
watch(
  () => params.fileList,
  async (newValue) => {
    console.log("newValue :>> ", newValue);
    var aa = document.querySelector(".el-upload--picture-card");
    if (newValue.length) {
      aa.style.display = "none";
    } else {
      setTimeout(() => {
        aa.style.display = "inline-flex";
      }, 1100);
    }
  }
);
// 切换图片比例
const changeRate = (item) => {
  params.value.aspect_ratio = item.value;
};
// 图片上传
const uploadImg = (file) => {
  if (!isLogin.value) {
    store.setShowLoginDialog(true);
    return;
  }

  // 压缩图片并上传
  new Compressor(file.file, {
    quality: 0.6,
    success(result) {
      const formData = new FormData();
      formData.append("file", result, result.name);
      // 执行上传操作
      httpPost("/api/upload", formData)
        .then((res) => {
          params.value.image = res.data.url;
          imgList.value.push(res.data.url);
          ElMessage.success("上传成功");
          if (uploadDialogVisivle.value) {
            uploadDialogVisivle.value = false;
            imgList.value = imgList.value.slice(-1);
          }
        })
        .catch((e) => {
          ElMessage.error("上传失败:" + e.message);
        });
    },
    error(err) {
      console.log(err.message);
    },
  });
};
const onChange = (uploadFile, uploadFiles) => {
  console.log("uploadFile :>> ", uploadFile);
  const reader = new FileReader();
  reader.readAsDataURL(uploadFile.raw);
  reader.onload = (e) => {
    // 后端入参 转base64  在提交的时候
    // const response = await uploadImgToBase64(file.raw)
    //       return response.result.replace(/.*;base64,/, '') //
  };
};

const handleRemove = (uploadFile, uploadFiles) => {
  console.log(uploadFile, uploadFiles);
};
const handleExceed = (files, uploadFiles) => {
  ElMessage.warning(`只能上传一张图片`);
};
const handlePictureCardPreview = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url;
  dialogVisible.value = true;
};
const runningJobs = ref([]);
const finishedJobs = ref([]);
const router = useRouter();

// 检查是否有画同款的参数
const _params = router.currentRoute.value.params["copyParams"];
if (_params) {
  params.value = JSON.parse(_params);
}
const power = ref(0);
const klingPower = ref(0); // 生成一个视频消耗算力

const socket = ref(null);
const userId = ref(0);
const heartbeatHandle = ref(null);
const connect = () => {
  let host = import.meta.env.VITE_APP_WS_HOST;
  if (host === "") {
    if (location.protocol === "https:") {
      host = "wss://" + location.host;
    } else {
      host = "ws://" + location.host;
    }
  }

  // 心跳函数
  const sendHeartbeat = () => {
    clearTimeout(heartbeatHandle.value);
    new Promise((resolve, reject) => {
      if (socket.value !== null) {
        socket.value.send(
          JSON.stringify({ type: "heartbeat", content: "ping" })
        );
      }
      resolve("success");
    }).then(() => {
      heartbeatHandle.value = setTimeout(() => sendHeartbeat(), 5000);
    });
  };

  const _socket = new WebSocket(
    host + `/api/${model}/client?user_id=${userId.value}`
  );
  _socket.addEventListener("open", () => {
    socket.value = _socket;

    // 发送心跳消息
    sendHeartbeat();
  });

  _socket.addEventListener("message", (event) => {
    if (event.data instanceof Blob) {
      const reader = new FileReader();
      reader.readAsText(event.data, "UTF-8");
      reader.onload = () => {
        const message = String(reader.result);
        if (message === "FINISH") {
          page.value = 0;
          isOver.value = false;
          fetchFinishJobs();
        }
        fetchRunningJobs();
      };
    }
  });

  _socket.addEventListener("close", () => {
    if (socket.value !== null) {
      connect();
    }
  });
};

const clipboard = ref(null);
onMounted(() => {
  initData();
  clipboard.value = new Clipboard(".copy-prompt-sd");
  clipboard.value.on("success", () => {
    ElMessage.success("复制成功！");
  });

  clipboard.value.on("error", () => {
    ElMessage.error("复制失败！");
  });

  httpGet("/api/config/get?key=system")
    .then((res) => {
      klingPower.value = res.data.kling_video_power;
      // console.log(res.data.kling_video_power);
      // params.value.negative_prompt = res.data.sd_neg_prompt
    })
    .catch((e) => {
      ElMessage.error("获取系统配置失败：" + e.message);
    });
});

onUnmounted(() => {
  clipboard.value.destroy();
  if (socket.value !== null) {
    socket.value.close();
    socket.value = null;
  }
});
const current = ref();
const videoClickHandle = (item, i) => {
  if (!item.img) {
    console.log("无数据");
    return;
  }
  console.log("item :>> ", item);
  current.value = i;
  videoData.value = item;
};
const downloadVideoHandle = (item) => {
  downloadVideo(item.img, `${item.prompt}.mp4`);
};
const tabChange = () => {
  page.value = 0;
  isOver.value = false;
  // params.value.prompt = "";
  Object.assign(params.value, resetParams);
  console.log(11);
  videoData.value = null;
  console.log(22);
  fetchRunningJobs();
  console.log(333);
  fetchFinishJobs();
};
const initData = () => {
  checkSession()
    .then((user) => {
      power.value = user["power"];
      userId.value = user.id;
      isLogin.value = true;
      page.value = 0;
      fetchRunningJobs();
      fetchFinishJobs();
      connect();
    })
    .catch(() => {});
};

const handleRoleChange = (val) => {
  console.log("val :>> ", val);
  if (val == "runway") {
    params.value.position = "keling";
    return;
  }
  fetchRunningJobs();
  page.value = 0;
  isOver.value = false;
  fetchFinishJobs();
};
const fetchRunningJobs = () => {
  if (!isLogin.value) {
    return;
  }

  // 获取运行中的任务
  httpGet(`/api/${model}/jobs?finish=0&type=${activeName.value}`)
    .then((res) => {
      const jobs = res.data;
      const _jobs = [];
      // for (let i = 0; i < jobs.length; i++) {
      //   if (jobs[i].progress === -1) {
      //     ElNotification({
      //       title: "任务执行失败",
      //       dangerouslyUseHTMLString: true,
      //       message: `任务ID：${jobs[i]["task_id"]}<br />原因：${jobs[i]["err_msg"]}`,
      //       type: "error",
      //     });
      //     // power.value += sdPower.value;
      //     continue;
      //   }
      //   _jobs.push(jobs[i]);
      // }
      runningJobs.value = jobs;
    })
    .catch((e) => {
      ElMessage.error("获取任务失败：" + e.message);
    });
};

const page = ref(0);
const pageSize = ref(10);
const isOver = ref(false);
// 获取已完成的任务
const fetchFinishJobs = () => {
  // if (_page) {
  //   page.value = _page;
  //   list.value = [];
  //   isOver.value = false;
  // }
  console.log("加载历史");
  if (!isLogin.value || isOver.value) {
    console.log("拦截");
    return;
  }
  loading.value = true;
  page.value = page.value + 1;
  // if (page) {
  //   page.value = _page;
  // }
  httpGet(
    `/api/${model}/jobs?finish=1&page=${page.value}&page_size=${pageSize.value}&type=video`
  )
    .then((res) => {
      if (res.data.length < pageSize.value) {
        console.log("结束");
        isOver.value = true;
      }
      const imageList = res.data;
      // for (let i = 0; i < imageList.length; i++) {
      //   imageList[i]["img_thumb"] =
      //     imageList[i]["img_url"] + "?imageView2/4/w/300/h/0/q/75";
      // }
      if (page.value == 1) {
        finishedJobs.value = imageList;
      } else {
        finishedJobs.value = finishedJobs.value.concat(imageList);
      }

      loading.value = false;
    })
    .catch((e) => {
      ElMessage.error("获取任务失败：" + e.message);
    });
};

// 创建绘图任务
const promptRef = ref(null);
const generate = () => {
  if (runningJobs.length) {
    ElMessage.error("有任务正在执行，请等待任务完成！");
    return;
  }
  if (params.value.prompt === "" && activeName.value === "text2video") {
    promptRef.value.focus();
    return ElMessage.error("请输入绘画提示词！");
  }

  if (!isLogin.value) {
    store.setShowLoginDialog(true);
    return;
  }

  if (params.value.seed === "") {
    params.value.seed = -1;
  }
  params.value.session_id = getSessionId();
  params.value.type = activeName.value;
  videoData.value = null;
  httpPost(`/api/${model}/videos`, params.value)
    .then(() => {
      ElMessage.success("生成视频推送成功，请耐心等待任务执行...");
      // power.value -= sdPower.value;
    })
    .catch((e) => {
      ElMessage.error("任务推送失败：" + e.message);
    });
};

const showTask = (row) => {
  item.value = row;
  showTaskDialog.value = true;
};

const copyParams = (row) => {
  params.value = row.params;
  showTaskDialog.value = false;
};

// 删除已上传图片
const removeUploadImage = (url) => {
  imgList.value = removeArrayItem(imgList.value, url);
};
const removeVideo = (item) => {
  ElMessageBox.confirm("此操作将会删除任务，继续操作吗?", "删除提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      httpGet(`/api/${model}/remove`, { id: item.id, user_id: item.user_id })
        .then(() => {
          ElMessage.success("任务删除成功");
          if (videoData.value && item.id == videoData.value.id) {
            videoData.value = null;
          }
          page.value = 0;
          isOver.value = false;
          fetchFinishJobs(1);
        })
        .catch((e) => {
          ElMessage.error("任务删除失败：" + e.message);
        });
    })
    .catch(() => {});
};

const formatCreativityTooltip = (val) => {
  // if (val > 0.7) {
  //   return val + " (数值较大)，有小概率出现图片和描述内容冲突导致的画面错误";
  // }
  return val;
};
</script>

<style lang="stylus" scoped>
@import "../assets/css/video-kling.styl"
@import "../assets/css/custom-scroll.styl"
</style>
